package cybertechcebu.task
{
	import cybertechcebu.FTPClient;
	import cybertechcebu.Console;

	public class TaskQueue
	{
		private var queue:Array = [];
		private var _currentTask:Task;
		private var _idle:Boolean = true;

		public function TaskQueue()
		{
		}

		public function get currentTask():Task
		{
			return _currentTask;
		}

		public function get idle():Boolean
		{
			return _idle;
		}

		public function addTask(task:Task):void
		{
			queue.push(task);
			if (queue.length == 1)
			{
				startNextTask();
			}

		}

		private function startNextTask():void
		{
			_currentTask = queue[0];
			if (_currentTask)
			{
				_currentTask.addEventListener(TaskEvent.TASK_START, handleStart);
				_currentTask.addEventListener(TaskEvent.TASK_PROGRESS, handleProgress);
				_currentTask.addEventListener(TaskEvent.TASK_END, handleEnd);
				_currentTask.addEventListener(TaskEvent.TASK_ERROR, handleError);
				_currentTask.start();
				_idle = false;
			}
			else
			{
				_idle = true;
			}
		}

		private function handleStart(e:TaskEvent):void
		{
			Console.progress("Task start: " + e.target.toString());
		}

		private function handleProgress(e:TaskEvent):void
		{
			Console.progress(e.progress);
		}

		private function handleEnd(e:TaskEvent):void
		{
			queue.shift();
			Console.progress("Task end: " + e.target.toString() + ", result - " + e.result);
			startNextTask();
		}

		private function handleError(e:TaskEvent):void
		{
			queue.shift();
			Console.error(e.error);
			startNextTask();
		}

	}
}
